#!/bin/bash

# ElasticSearch + Kibana 测试脚本
echo "🧪 运行 ElasticSearch + Kibana 功能测试..."

# 检查服务是否运行
if ! curl -s http://localhost:9200 > /dev/null; then
    echo "❌ ElasticSearch 未运行，请先执行 ./start.sh"
    exit 1
fi

if ! curl -s http://localhost:5601/api/status > /dev/null; then
    echo "❌ Kibana 未运行，请先等待服务完全启动"
    exit 1
fi

echo "✅ 服务运行正常，开始功能测试..."

# 测试1: 创建索引
echo "📝 测试1: 创建测试索引..."
curl -X PUT "localhost:9200/test-index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "user": {
        "type": "text"
      },
      "message": {
        "type": "text"
      },
      "timestamp": {
        "type": "date"
      },
      "level": {
        "type": "keyword"
      }
    }
  }
}
' > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "✅ 索引创建成功"
else
    echo "❌ 索引创建失败"
fi

# 测试2: 插入测试数据
echo "📝 测试2: 插入测试数据..."
for i in {1..5}; do
    curl -X POST "localhost:9200/test-index/_doc/$i" -H 'Content-Type: application/json' -d"
    {
      \"user\": \"用户$i\",
      \"message\": \"这是第$i条测试消息\",
      \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)\",
      \"level\": \"info\"
    }
    " > /dev/null 2>&1
done

echo "✅ 测试数据插入完成"

# 等待索引刷新
sleep 2

# 测试3: 搜索数据
echo "📝 测试3: 搜索功能测试..."
result=$(curl -s -X GET "localhost:9200/test-index/_search?pretty" | grep -c "用户")
if [ $result -gt 0 ]; then
    echo "✅ 搜索功能正常，找到 $result 条记录"
else
    echo "❌ 搜索功能异常"
fi

# 测试4: 聚合查询
echo "📝 测试4: 聚合查询测试..."
agg_result=$(curl -s -X GET "localhost:9200/test-index/_search" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "level_count": {
      "terms": {
        "field": "level"
      }
    }
  }
}
' | grep -o '"doc_count":[0-9]*' | head -1)

if [ ! -z "$agg_result" ]; then
    echo "✅ 聚合查询正常"
else
    echo "❌ 聚合查询异常"
fi

# 测试5: Kibana API
echo "📝 测试5: Kibana API 测试..."
kibana_status=$(curl -s "localhost:5601/api/status" | python3 -c "import sys, json; print(json.load(sys.stdin)['status']['overall']['level'])" 2>/dev/null)
if [ "$kibana_status" = "available" ]; then
    echo "✅ Kibana API 正常"
else
    echo "⚠️  Kibana API 状态: $kibana_status"
fi

# 显示结果摘要
echo ""
echo "📊 测试结果摘要:"
echo "================================"

# 显示集群信息
echo "🔍 集群状态:"
curl -s "localhost:9200/_cluster/health" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    print(f\"   集群名称: {data.get('cluster_name', 'N/A')}\")
    print(f\"   状态: {data.get('status', 'N/A')}\")
    print(f\"   节点数: {data.get('number_of_nodes', 'N/A')}\")
    print(f\"   数据节点数: {data.get('number_of_data_nodes', 'N/A')}\")
    print(f\"   活跃主分片: {data.get('active_primary_shards', 'N/A')}\")
    print(f\"   活跃分片: {data.get('active_shards', 'N/A')}\")
except:
    print('   无法解析集群状态')
"

echo ""
echo "📈 索引统计:"
curl -s "localhost:9200/test-index/_stats" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    total = data['_all']['total']
    print(f\"   文档总数: {total.get('docs', {}).get('count', 'N/A')}\")
    print(f\"   存储大小: {total.get('store', {}).get('size_in_bytes', 'N/A')} bytes\")
except:
    print('   无法解析索引统计')
"

echo ""
echo "🎯 快速访问:"
echo "   ElasticSearch: http://localhost:9200"
echo "   Kibana:        http://localhost:5601"
echo "   测试索引:      curl http://localhost:9200/test-index/_search?pretty"

echo ""
echo "🧹 清理测试数据:"
echo "   删除测试索引: curl -X DELETE 'localhost:9200/test-index'"

echo ""
echo "🎉 测试完成！"
